package com.example.rbacmanage.config;

import com.example.rbacmanage.entity.Role;
import com.example.rbacmanage.entity.User;
import com.example.rbacmanage.mapper.RoleMenuMapper;
import com.example.rbacmanage.mapper.UserMapper;
import com.example.rbacmanage.vo.MyUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyUserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Override
    public MyUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("用户名不能为空");
        }
        User user = userMapper.queryOneByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        List<Role> roles = userMapper.queryRolesByUserId(user.getId());
        List<Long> roleIds = roles.stream().map(Role::getId).collect(Collectors.toList());
        user.setRoleIds(roleIds);
        MyUserDetails myUserDetails = new MyUserDetails(user);
        myUserDetails.setId(user.getId().intValue());
        myUserDetails.setUsername(user.getUserName());
        myUserDetails.setPassword(user.getPassword());
        roles.forEach(role -> {
            List<String> permissions = roleMenuMapper.queryPermissionsByRoleId(role.getId());
            role.setPermissions(permissions);
        });
        myUserDetails.setRoles(roles);
        return myUserDetails;
    }
}
